<script lang="ts" setup>
import { computed, ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { detailApi, createApi, editApi } from '#/api/system/agreement';

const formData = ref();

const [Form, formApi] = useVbenForm({
  schema: [
    {
      fieldName: 'id',
      label: 'ID',
      defaultValue: 0,
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: [''],
      },
    },
    {
        fieldName: 'name',
        label: '名称',
        component: 'Input',
        componentProps: {
            placeholder: '请输入名称',
        },
        rules: 'required',
    },
    {
        fieldName: 'title',
        label: '标题',
        component: 'Input',
        componentProps: {
            placeholder: '请输入标题',
        },
        rules: 'required',
    }, 
    {
        fieldName: 'content',
        label: '内容',
        component: 'Editor',
        defaultValue: '',
    },
    {
        fieldName: 'remark',
        label: '备注',
        component: 'Textarea',
        componentProps: {
            placeholder: '请输入备注',
        },
    },
  ],
  showDefaultActions: false,
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) return;
    const values = await formApi.getValues();
    drawerApi.lock();
    (values.id ? editApi(values) : createApi(values))
      .then((res) => {
        message.success({
          content: res.message,
        });
        drawerApi.close();
      })
      .catch(() => {
        drawerApi.unlock();
      });
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData();
      formApi.resetForm();
      formData.value = data;
      if (data.id) {
        detailApi(data.id).then((res) => {
          formApi.setValues(res);
        })
      }
    }
  },
  overlayBlur: 1,
  class: 'w-[550px]',
});

const getDrawerTitle = computed(() => {
  return formData.value?.id
    ? '编辑协议'
    : '新增协议';
});


</script>
<template>
  <Drawer :title="getDrawerTitle">
    <Form />
  </Drawer>
</template>
